package com.you.tomcat.netty.main;

import com.you.tomcat.netty.http.HttpServlet;
import com.you.tomcat.netty.http.MyRequest;
import com.you.tomcat.netty.http.MyResponse;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import java.io.FileInputStream;
import java.net.ServerSocket;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Tomcat启动服务
 */
public class NettyTomcatServer {

    private int port = 9000;
    private ServerSocket server;

    private Properties webxml = new Properties();

    //服务的映射
    private Map<String, HttpServlet> servletMapping = new ConcurrentHashMap<String, HttpServlet>();

    public static void main(String[] args) throws Exception {
        new NettyTomcatServer().start();
    }

    /**
     * 初始化配置信息
     *
     * @throws Exception
     */
    public void init() throws Exception {
        //得到当前WEB-INF类路径
        String webInf = this.getClass().getResource("/").getPath();
        FileInputStream fis = new FileInputStream(webInf + "web.properties");
        //加载web.properties配置文件
        webxml.load(fis);
        //2、配置web.xml 自己写的Servlet继承HttpServlet
        //   servlet-name
        //   servlet-class
        //   url-pattern
        //3、读取配置，url-pattern  和 Servlet建立一个映射关系
        for (Object k : webxml.keySet()) {
            String key = k.toString();
            if (key.endsWith(".url")) {
                String servletName = key.replaceAll("\\.url$", "");
                String url = webxml.getProperty(key);
                String className = webxml.getProperty(servletName + ".className");
                //单实例，多线程
                HttpServlet httpServlet = (HttpServlet) Class.forName(className).newInstance();
                servletMapping.put(url, httpServlet); //url与servletClass的映射关系
            }
        }
    }

    public void start() throws Exception {
        //1.加载配置文件
        init();
        //Netty封装了NIO，Reactor模型，Boss，worker
        //Boss线程
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //work线程
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            // 链路式编程
            bootstrap.group(bossGroup, workGroup)
                    // 主线程处理类,看到这样的写法，底层就是用反射
                    .channel(NioServerSocketChannel.class)
                    // 子线程处理类 , Handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 客户端初始化处理
                        @Override
                        protected void initChannel(SocketChannel client) throws Exception {
                            // 无锁化串行编程
                            //Netty对HTTP协议的封装，顺序有要求
                            // HttpResponseEncoder 编码器
                            client.pipeline().addLast(new HttpResponseEncoder());
                            // HttpRequestDecoder 解码器
                            client.pipeline().addLast(new HttpRequestDecoder());
                            //业务处理类
                            client.pipeline().addLast(new MyProcessHandler());
                        }
                    })
                    // 针对主线程的配置 分配线程最大数量 128
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 针对子线程的配置 保持长连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            // 启动服务器
            ChannelFuture f = bootstrap.bind(port).sync();
            System.out.println("Tomcat 已启动，监听的端口是：" + port);
            //防止主线程停止，除非channel关闭
            f.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 关闭boss和work线程池
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public class MyProcessHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof HttpRequest) {
                HttpRequest req = (HttpRequest) msg;
                System.out.println(req);
                // 转交给我们自己的request实现
                MyRequest request = new MyRequest(ctx, req);
                // 转交给我们自己的response实现
                MyResponse response = new MyResponse(ctx, req);
                // 实际业务处理
                String url = request.getUrl();

                if (servletMapping.containsKey(url)) {
                    servletMapping.get(url).service(request, response);
                } else {
                    response.write("404 - Not Found");
                }
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("---------处理异常------" + cause.getMessage());
        }
    }
}
